package org.peterf.foxish.activity;

import org.peterf.foxish.engine.Engine;
import org.peterf.foxish.engine.Engine.EngineState;
import org.peterf.foxish.scene.Scene;
import org.peterf.foxish.surface.SurfaceView;
import org.peterf.foxish.util.ActivityUtil;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;

/**
 * The basic activity with a frame-layout {@link SurfaceView}.
 * <p>
 * Subclass should implement {@link #onCreateEngine()} to provide an initialized
 * {@link Engine}. The settings of the {@link Engine} will be applied
 * automatically then.
 * <p>
 * You can attach a {@link Scene} to the {@link Engine} you provide, so that it
 * would start working once the {@link SurfaceView} is available for rendering.
 * 
 * @author peter
 * 
 */
public abstract class BasicActivity extends Activity {

    protected Engine engine;

    /**
     * The engine is created here. By default, uncaught exceptions will be set
     * to be handled. Upon exception, {@link BugReportActivity} will show up.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        engine = onCreateEngine();
        ActivityUtil.applyScreenSetting(this, engine.getScreenSetting());
        setContentView(engine.getSurface(), engine.getScreenSetting()
                .getLayoutParams());
    }

    /**
     * The global instance of {@link Engine} will be destroyed here.
     */
    @Override
    public void onDestroy() {
        Engine.destroyInstance();
        super.onDestroy();
    }

    /**
     * The engine will pause.
     */
    @Override
    public void onPause() {
        engine.onPause();
        super.onPause();
    }
    
    /**
     * If the window has the focus, the engine being paused will be resumed
     * here.
     */
    @Override
    public void onResume() {
        super.onResume();
        if (engine.getState() == EngineState.PAUSED && hasWindowFocus()) {
            engine.onResume();
        }
    }

    /**
     * If the window has the focus, the engine being paused will be resumed
     * here.
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (engine.getState() == EngineState.PAUSED && hasFocus) {
            engine.onResume();
        }
    }

    /**
     * You should provide the initialized {@link Engine} here. You can attach
     * the {@link Scene} you want to use once the {@link SurfaceView} is
     * available for rendering.
     * 
     * @return The initialized {@link Engine}.
     */
    protected abstract Engine onCreateEngine();

}
